package com.txw.javaCore.server.redisson;

import com.txw.javaCore.api.enums.Constant;
import com.txw.javaCore.model.mapper.UserOrderMapper;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.redisson.api.map.event.EntryEvent;
import org.redisson.api.map.event.EntryExpiredListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @PROJECT_NAME: JavaCoreB2
 * @DESCRIPTION: redisson中间件通用的监听MapCache里头时时刻刻可能会失效的元素
 * @Author: 涂玄武
 * @DATE: 2021/2/2 16:34
 */
@Component
public class RedissonMapCacheService implements ApplicationRunner, Ordered {

    private static final Logger log = LoggerFactory.getLogger(RedissonMapCacheService.class);

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("--在项目一直跑的过程中，不间断地执行一些我们自定义的服务逻辑 --");

        this.listenExpireUserOrder();
    }

    /**
     * 监听并失效迟迟未支付的用户订单
     */
    private void listenExpireUserOrder() {
        try {
            RMapCache<Object, Object> rMapCache = redisson.getMapCache(Constant.RedisMapCacheUserOrder);
            rMapCache.addListener(new EntryExpiredListener<Integer, String>() {
                @Override
                public void onExpired(EntryEvent<Integer, String> event) {
                    log.info("---失效监听用户过期的订单,监听到消息：key={},订单编号={}", event.getKey(), event.getValue());

                    userOrderMapper.updateExpireOrder(event.getValue(),Constant.OrderPayStatus.UnPay.getCode(),Constant.OrderPayStatus.SystemCancel.getCode());
                }
            });

        } catch (Exception e) {
            log.error("Redisson-失效监听用户过期的订单-发生异常：", e.fillInStackTrace());
        }
    }


}
